package com.lwt.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwt.constant.TongchouConstant;
import com.lwt.entity.Admin;
import com.lwt.entity.AdminExample;
import com.lwt.exception.LoginAcctAlreadyInUseException;
import com.lwt.exception.LoginAcctAlreadyInUseForUpdateException;
import com.lwt.exception.LoginFailedException;
import com.lwt.mapper.AdminMapper;
import com.lwt.service.api.AdminService;
import com.lwt.util.TongchouUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author Li Weitong
 * @Date 2021/1/13 22:02
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    private Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Override
    public int saveAdmin(Admin admin) {
//int i=1;
//i=i/0;
        String userPswd = admin.getUserPswd();
        userPswd = TongchouUtil.md5(userPswd);
        admin.setUserPswd(userPswd);

        Date date = new Date();// 生成创建时间
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        admin.setCreateTime(nowTime);

        int i = 0;
        try {
            i = adminMapper.insert(admin);// 保存
        } catch (Exception exception) {
            exception.printStackTrace();
            logger.info("异常全类名："+exception.getClass().getName());
            if (exception instanceof DuplicateKeyException) { // 注意：这里判断当前异常类型是DuplicateKeyException类型才向外抛出自定义异常
                throw new LoginAcctAlreadyInUseException(TongchouConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
        logger.debug("管理员增加成功"+i+"条");
        return i;
    }

    @Override
    public List<Admin> getAllAdmin() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        // 1.根据登录账号查询Admin对象
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andLoginAcctEqualTo(loginAcct);
        List<Admin> list = adminMapper.selectByExample(adminExample);
        // 2.判断Admin对象是否为null
        if (list == null || list.size() == 0) {
            throw new LoginFailedException(TongchouConstant.MESSAGE_LOGIN_FAILED);
        }
        if (list.size() > 1) {
            throw new RuntimeException(TongchouConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        // 3.如果Admin为空则抛出异常
        Admin admin = list.get(0);
        if (admin == null) {
            throw new LoginFailedException(TongchouConstant.MESSAGE_LOGIN_FAILED);
        }
        // 4.如果Admin不为空则将数据库密码从Admin对象取出
        String userPswdDB = admin.getUserPswd();
        // 5.将表单提交的明文密码加密
        String userPswdForm = TongchouUtil.md5(userPswd);
        // 6.对密码进行比较?
        if (!Objects.equals(userPswdDB, userPswdForm)) {
            // 7.如果比较结果不一致则抛出异常
            throw new LoginFailedException(TongchouConstant.MESSAGE_LOGIN_FAILED);
        }

        // 8.如果密码一致则返回admin对象
        return admin;
    }

    /**
     * 使用PageInfo开启分页，封装到pageInfo对象中
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize); // 开启分页功能，体现了PageHelper的非侵入式设计
        List<Admin> list = adminMapper.selectAdminByKeywords(keyword); // list是一个Page类型，Page继承了ArrayList
        return new PageInfo<>(list); // 封装到PageInfo对象中
    }

    /**
     * 普通请求单一删除
     * @param adminId
     * @return
     */
    @Override
    public int remove(Integer adminId) {
        return adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public int update(Admin admin) {
        int i = 0;

        try {
            i = adminMapper.updateByPrimaryKeySelective(admin);// 有选择的更新，对应null值的字段不更新
        } catch (Exception exception) {
            exception.printStackTrace();
            if (exception instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseForUpdateException(TongchouConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
        System.out.println("您更新了"+i+"条");
        return i;
    }
}
